package com.thunisoft.netty.custom;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

/**
 * 自定义解码器
 * @title CustomDecoder.java
 * @package com.thunisoft.netty.custom
 * @projectName spring.boot
 * @author yzj 
 * @date 2019年10月8日 下午4:58:54
 */
public class CustomDecoder extends ByteToMessageDecoder {

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		 // 获取协议的版本
        int version = in.readInt();
        // 获取消息长度
        int contentLength = in.readInt();
        // 获取SessionId
        byte[] sessionByte = new byte[36];
        in.readBytes(sessionByte);
        String sessionId = new String(sessionByte);

        // 组装协议头
        CustomHeader header = new CustomHeader(version, contentLength, sessionId);

        // 读取消息内容
        byte[] content = in.readBytes(in.readableBytes()).array();
       // int toRead=in.readableBytes();
       // ByteBuf content = in.readRetainedSlice(toRead);
        //byte[] content = in.readBytes();
       
        CustomMessage message = new CustomMessage(header, new String(content));

        out.add(message);
	}

}
